<template>
  <div class="h-full subjectAll-box">
    <base-page v-bind="baseInfo">
      <template #searchBar>
        <filter-form
          ref="filterForm"
          :elements="elements"
          :show-reset="true"
          @submit="submit"
        >
          <template>
            <el-button v-waves type="primary" icon="el-icon-plus" @click="drawerAdd">新增</el-button>
          </template>
        </filter-form>
      </template>

      <template #content>
        <div class="table-box">
          <TableNew
            :loading="tableLoading"
            :data="tableData"
            :columns="columns"
            :pagination="pagination"
            :header-cell-style="{'text-align':'center'}"
            :cell-style="{'text-align':'center'}"
            row-key="id"
            children="childList"
            @paginationChange="paginationChange"
          >
            <template #action="scope">
              <el-tooltip class="item" effect="dark" content="编辑" placement="top" :open-delay="600">
                <i class="el-icon-edit-outline action" @click="editFun(scope.row)" />
              </el-tooltip>

              <el-tooltip class="item" effect="dark" content="删除" placement="top" :open-delay="600">
                <i class="el-icon-delete action  text-red-500" @click="removeYsSubjectByIdFun(scope.row)" />
              </el-tooltip>
            </template>
          </TableNew>
        </div>
      </template>
    </base-page>

    <Drawer
      :visible="drawerVisible"
      :title="drawerTitle"
      width="35%"
      :footer-btns="footerBtns"
      @submit="drawerSubmit"
      @cancel="drawerCancel"
    >
      <template>
        <el-form ref="drawerForm" :model="drawerForm" size="mini" :rules="drawerRules" label-width="110px" class="mx-15 mt-10">
          <el-form-item label="预算科目级别" :required="true">
            <el-radio-group v-model="drawerForm.parentChild" :disabled="drawerType === 'edit'">
              <el-radio :label="true">父级</el-radio>
              <el-radio :label="false">子级</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item v-if="!drawerForm.parentChild" label="是否为末级" prop="child" :required="true">
            <el-radio-group v-model="drawerForm.child" :disabled="drawerType === 'edit' && drawerSelect.childList && !!drawerSelect.childList.length">
              <el-radio :label="false">否</el-radio>
              <el-radio :label="true">是</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="预算科目名称" prop="subjectName">
            <el-input v-model="drawerForm.subjectName" placeholder="请输入预算科目名称" />
          </el-form-item>

          <el-form-item label="预算科目编码" prop="subjectCode">
            <el-input v-model="drawerForm.subjectCode" placeholder="请输入预算科目编码" />
          </el-form-item>

          <el-form-item v-if="!drawerForm.parentChild && drawerForm.child" label="类型" prop="type">
            <el-select v-model="drawerForm.type" placeholder="请选择类型" multiple class="w-full">
              <el-option v-for="item in typeList" :key="'type' + item.id" :label="item.dictionaryName" :value="item.id" />
            </el-select>
          </el-form-item>

          <el-form-item v-if="!drawerForm.parentChild && drawerForm.child && subjectTypeShow" label="预算科目类别" prop="subjectType">
            <el-select v-model="drawerForm.subjectType" placeholder="请选择预算科目类别" class="w-full">
              <el-option v-for="item in subjectTypeList" :key="'subjectType' + item.id" :label="item.dictionaryName" :value="item.id" />
            </el-select>
          </el-form-item>

          <el-form-item v-if="!drawerForm.parentChild && drawerForm.child && subjectTypeShow" label="管理部门名称" prop="departments">
            <el-select v-model="drawerForm.departments" placeholder="请选择管理部门名称" multiple class="w-full" @change="departmentsChange">
              <el-option v-for="item in departmentsList" :key="'departments' + item.id" :label="item.departmentName" :value="item.id" />
            </el-select>
          </el-form-item>

          <el-form-item v-if="drawerType === 'edit' && !drawerForm.parentChild && drawerForm.child" label="管理部门编码">
            <el-input v-model="drawerForm.departmentCodes" disabled />
          </el-form-item>

          <el-form-item v-if="!drawerForm.parentChild" label="上级预算科目" prop="parent">
            <el-cascader
              v-model="drawerForm.parent"
              :options="parentList"
              class="w-full"
              placeholder="请选择上级预算科目"
              :props="{
                checkStrictly: true,
                label: 'subjectName',
                value: 'id',
                children: 'childList'
              }"
            />
          </el-form-item>

          <el-form-item label="备注" prop="remark">
            <el-input v-model="drawerForm.remark" type="textarea" placeholder="请输入备注" :rows="5" />
          </el-form-item>
        </el-form>
      </template>
    </Drawer>
  </div>
</template>

<script>
import {
  listYsDepartment,
  listYsDictionary,
  listYsSubject,
  listYsSubjectPage, removeYsSubjectById,
  saveOrUpdateYsSubject
} from '@/api/settings'
import listMixins from '@/mixins/budgetQuert/listMixins'

export default {
  name: 'Subject', // 预算科目管理
  components: {},
  mixins: [listMixins],
  data() {
    return {
      baseInfo: {
        searchBarShow: true
      },
      searchParams: '',
      elements: [
        {
          label: '预算科目名称',
          type: 'input',
          width: 150,
          key: 'subjectName',
          value: ''
        },
        {
          label: '预算科目编码',
          type: 'input',
          width: 150,
          key: 'subjectCode',
          value: ''
        }
      ],
      tableData: [],
      columns: [
        {
          title: '预算科目名称',
          dataIndex: 'subjectName',
          align: 'left'
        },
        {
          title: '预算科目编码',
          dataIndex: 'subjectCode'
        },
        {
          title: '类型',
          dataIndex: 'type'
        },
        {
          title: '管理部门名称',
          dataIndex: 'departmentNames'
        },
        {
          title: '管理部门编码',
          dataIndex: 'departmentCodes'
        },
        {
          title: '预算科目类别',
          dataIndex: 'subjectTypeName'
        },
        {
          title: '备注',
          dataIndex: 'remark'
        },
        {
          title: '创建时间',
          dataIndex: 'createTime'
        },
        {
          title: '操作',
          dataIndex: 'action',
          type: 'otherTag'
        }
      ],
      footerBtns: [
        {
          text: '保存',
          type: 'primary',
          loading: false,
          trigger: 'submit'
        },
        {
          text: '取消',
          type: 'info',
          trigger: 'cancel'
        }
      ],

      drawerVisible: false,
      drawerTitle: '',
      drawerSelect: '',
      drawerType: 'add',
      initialDrawerForm: '',
      subjectTypeShow: false,
      drawerForm: {
        parentChild: true,
        child: false,
        parent: '',
        subjectName: '',
        subjectCode: '',
        subjectType: '',
        type: [],
        departments: [],
        departmentsCode: '',
        departmentCodes: '',
        remark: ''
      },
      drawerRules: {
        parent: [
          { required: true, message: '请选择上级预算科目', trigger: 'change' }
        ],
        subjectName: [
          { required: true, message: '请输入预算科目名称', trigger: 'blur' }
        ],
        subjectCode: [
          { required: true, message: '请输入预算科目编码', trigger: 'blur' }
        ],
        desc: [
          { required: true, message: '请填写活动形式', trigger: 'blur' }
        ],
        subjectType: [
          { required: true, message: '请选择预算科目类别', trigger: 'change' }
        ],
        type: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ],
        departments: [
          { required: true, message: '请选择管理部门名称', trigger: 'change' }
        ]
      },
      parentList: [],
      subjectTypeList: [],
      typeList: [],
      departmentsList: []
    }
  },
  watch: {
    'drawerForm.child'(val) {
      if (!val) {
        this.drawerForm.type = []
      }
    },
    'drawerForm.type'(val) {
      this.subjectTypeShow = val.indexOf(6) !== -1

      if (val.indexOf(6) === -1) {
        this.drawerForm.subjectType = ''
        this.drawerForm.departments = []
      }
    }
  },
  mounted() {
    this.initialDrawerForm = JSON.parse(JSON.stringify(this.drawerForm))
  },
  methods: {
    getData(val) {
      this.searchParams = val

      listYsSubjectPage({
        size: this.pagination.pageSize,
        num: this.pagination.current,
        ...val
      }).then(res => {
        if (res.code === 200) {
          this.tableData = res.data.records
          this.pagination.total = res.data.total
        } else {
          this.$message.error('获取数据失败')
        }
      })
    },

    /**
     * 字典
     */
    listYsDictionaryFun(selectType) {
      listYsDictionary({
        selectType
      }).then(res => {
        if (res.code === 200) {
          this[selectType + 'List'] = res.data
        }
      })
    },

    /**
     * 预算科目
     */
    listYsSubjectFun() {
      listYsSubject().then(res => {
        if (res.code === 200) {
          this.parentList = res.data
        }
      })
    },

    /**
     * 预算部门
     */
    listYsDepartmentFun() {
      listYsDepartment().then(res => {
        if (res.code === 200) {
          this.departmentsList = res.data
        }
      })
    },

    /**
     * 管理部门
     */
    departmentsChange() {
      const code = []

      this.drawerForm.departments.forEach(item => {
        this.departmentsList.forEach(item1 => {
          if (item === item1.id) {
            code.push(item1.departmentCode)
          }
        })
      })

      this.drawerForm.departmentsCode = code.join(';')
    },

    /**
     * 抽屉 提交
     */
    drawerSubmit() {
      this.$refs.drawerForm.validate((valid) => {
        if (valid) {
          this.drawerForm.firstId = this.drawerForm.parent && this.drawerForm.parent[0]
          this.drawerForm.parent = this.drawerForm.parent && this.drawerForm.parent[this.drawerForm.parent.length - 1]
          this.footerBtns[0].loading = true
          saveOrUpdateYsSubject(this.drawerForm).then(res => {
            if (res.code === 200) {
              this.getData(this.searchParams)
              this.drawerCancel()
            } else {
              this.$message.error('提交失败')
            }

            this.footerBtns[0].loading = true
          })
        }
      })
    },

    /**
     * 删除
     */
    removeYsSubjectByIdFun(row) {
      removeYsSubjectById({ id: row.id }).then(res => {
        if (res.code === 200) {
          this.$refs.filterForm.submitFormFilter()
          this.$message.success('删除成功')
        } else {
          this.$message.error('删除失败')
        }
      })
    },

    /**
     * 新增
     */
    drawerAdd() {
      this.drawerTitle = '新增预算科目'
      this.drawerForm = this.initialDrawerForm
      this.drawerShow()
    },

    /**
     * 抽屉 打开
     */
    drawerShow() {
      this.listYsSubjectFun()
      this.listYsDepartmentFun()
      this.listYsDictionaryFun('subjectType')
      this.listYsDictionaryFun('type')

      this.drawerVisible = true
    },

    /**
     * 抽屉 关闭
     */
    drawerCancel() {
      this.drawerType = 'add'
      this.$refs.drawerForm.resetFields()
      this.drawerVisible = false
    },

    /**
     * 编辑
     */
    editFun(info) {
      const row = JSON.parse(JSON.stringify(info))
      this.drawerType = 'edit'
      this.drawerTitle = '编辑预算科目'
      row.departments = row.deptIds
      row.type = row.typeIds
      row.subjectType = Number(row.subjectType)
      this.drawerSelect = JSON.parse(JSON.stringify(row))
      this.drawerForm = JSON.parse(JSON.stringify(row))

      if (this.drawerForm.childList) {
        delete this.drawerForm.childList
      }

      this.drawerShow()
    }
  }
}
</script>

<style lang="less" scoped>
.table-box{
  height: 100%;
  display: flex;
  flex-direction: column;
}
</style>
<style lang="less">
.subjectAll-box {
  .el-table__body {
    td:first-of-type {
      text-align: left !important;
    }
  }
}
</style>
